﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Security.Cryptography;
using System.Text;
using LKVMLMADMIN.Models;
using LKVMLMLib;
using System.Configuration;
using System.Net.Http;
using System.Web.Helpers;
using PinService.Lib;

namespace LKVMLMADMIN.Controllers.Json
{
    public class JsonAccountController : BaseController
    {
        public LKVService.User userDB = new LKVService.User(); 
        public ActionResult GetUserByID(int UserId)
        {
            var result = new ProfileModel();
            try
            {
                var transactionDB = new LKVService.Transaction();
                var user = userDB.findUserById(UserId);
                result.UserId = user.UserId;
                result.UserName = user.UserName;
                result.Email = user.EMAIL;
                result.HoTen = user.HOTEN == null ? user.UserName : user.HOTEN;
                if (user.Parent_ID!=null)
                {
                    result.Parent_ID = (int)user.Parent_ID;
                }
                else
                {
                    result.Parent_ID = 0;
                }                
                if (user.QUOCGIA!=null)
                result.QUOCGIA = user.QUOCGIA;
                if (user.LevelUpdate!=null)
                {
                    TimeSpan UpTime = user.LevelUpdate.Value - DateTime.Now;
                    result.UpTime = UpTime.Days.ToString() + "day " + UpTime.Hours.ToString() + "hours " + UpTime.Minutes.ToString() + "minute";
                }
                var systemService = new LKVService.SystemService();                
                result.SessionId = systemService.SetSession(user.UserId);
                result.SoCMNDVOHOACCHONG = user.NganHang;
                result.SoTaiKhoan = user.SoTaiKhoan;
                result.Name_IDParent = "0";
                result.SDTNHARIENG = user.SDTNHARIENG;
                result.DiaChi = user.DIACHI;
                result.BankID = user.BankID;
                if(user.BankID != null)
                    result.BankName = userDB.findBankById(user.BankID.Value) == null ? "" : userDB.findBankById(user.BankID.Value).Name;
                if (user.Parent_ID != 0 && user.Parent_ID != null)
                {
                    int uidpr = Convert.ToInt32(user.Parent_ID);
                    string usernameparent = userDB.findParent(uidpr).UserName;
                    result.Name_IDParent = usernameparent;
                }     
                result.LevelName = "";             
            }
            catch (Exception ex)
            {
                return Json(new { Messeger = ex.Message, Status=false });
            }
            return Json(result);
        }
        // GET: /Account/        
        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(string username, string password)
        {
            try
            {
                string a = Convert.ToString(password);
                string b = MD5Hash(a);
                //LKVMLMLib.UserProfile result = userDB.getUser(username, b);
                var user = userDB.getUser(username, b);
                if (user != null)
                {
                    //save session
                    var systemService = new LKVService.SystemService();                   
                    var result = new ProfileModel();
                    result.SessionId = systemService.SetSession(user.UserId);
                    result.UserId = user.UserId;
                    result.UserName = user.UserName;
                    result.Email = user.EMAIL;
                    result.HoTen = user.HOTEN;
                    result.Parent_ID = user.Parent_ID;                                   
                    DateTime UpTime = Convert.ToDateTime(user.CreateDate);
                    result.CreateDate = UpTime;
                    result.SoTaiKhoan = user.SoTaiKhoan;
                    result.BankID = user.BankID;
                    //var session  = systemService.GetSession(user.UserId);
                    if (user.Parent_ID != 0 && user.Parent_ID != null)
                    {
                        int uidpr = Convert.ToInt32(user.Parent_ID);
                        string usernameparent = userDB.findParent(uidpr).UserName;
                        result.Name_IDParent = usernameparent;
                    }
                    else
                    {
                        result.Name_IDParent = "0";
                    }
                    return Json(result);
                }
            }
            catch (InvalidCastException e)
            {
                return Json(e);
            }
            return Json("0");
        }
        public static string MD5Hash(string text)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));
            byte[] result = md5.Hash;
            StringBuilder strBuilder = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                strBuilder.Append(result[i].ToString("x2"));
            }

            return strBuilder.ToString();
        }
        public ActionResult EditProfile(UserProfile user, string LR = "")
        {
            string notice = "";
            try
            {
                var ckPH = userDB.checkUserInPH(user.UserId);
                if (ckPH == true)
                {
                    notice = "Information cannot be changed while PH";
                    return Json(notice);
                }               
                UserProfile saveUser = userDB.findUserById(user.UserId);                
                //saveUser.UserName = user.UserName;
                saveUser.SDTNHARIENG = user.SDTNHARIENG;
                saveUser.DIACHI = user.DIACHI;
                //edit full name
                saveUser.HOTEN = user.HOTEN;
                saveUser.BankID = user.BankID;
                saveUser.SoTaiKhoan = user.SoTaiKhoan;        
                var rs = userDB.UpdateUser(saveUser);
                switch (rs)
                {
                    case 0:
                        notice = "Edit User does not exist !";
                        break;
                    case 1:
                        notice = "Can not change from father to son !";
                        break;
                    case 2:
                        notice = "This member has enough 2 children !";
                        break;
                    case 3:
                        notice = "Can not move root !";
                        break;
                    case 4:
                        notice = "Left / Right is not empty !";
                        break;
                    default:
                        notice = "Data Change Success !";
                        break;
                }
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
            return Json(notice);
        }
        [HttpPost]
        public ActionResult PremiumEdit(UserProfile user, string LR = "")
        {
            string notice = "";
            try
            {
                UserProfile saveUser = userDB.findUserById(user.UserId);
                //edit username
                saveUser.EMAIL = user.EMAIL;
                var rs = userDB.UpdateUser(saveUser);
                switch (rs)
                {
                    case 0:
                        notice = "User Edit không tồn tại !";
                        break;
                    case 1:
                        notice = "Không thể thay đổi từ cha xuống con !";
                        break;
                    case 2:
                        notice = "Thành viên này đã đủ 2 con !";
                        break;
                    case 3:
                        notice = "Không thể di chuyển root !";
                        break;
                    case 4:
                        notice = "Left/Right không trống !";
                        break;
                    default:
                        notice = "Thay đổi dữ liệu thành công !";
                        break;
                }
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
            return Json(notice);
        }
        public ActionResult validationAccount(int userId,int WalletId, int PaymentId)
        {
            try
            {
                var user = userDB.findUserById(userId);
                if (user.EMAIL==null)
                {
                    return Json(new { Result = "", Status = false, Messeger = "Email is not null" });
                }
                //kiem tra so du tai khoan
                var transaction = new LKVService.Transaction();
                var wallet = transaction.getWalletDetail(userId, WalletId);
                var fee = userDB.getFeeConfig();
                if (fee.PremiumEdit > wallet.Balance)
                {
                    return Json(new { Result = "", Status = false, Messeger = "Wallet Balance is not enough" });
                }

                //send pin code
                //send pincode
                string pinCode = LKVMLMADMIN.Common.StringHelper.RandomString(10);
                string subject = "Change Email";
                string ContentMail = string.Format("Pin Code: {0}", pinCode);
                var Author = new Authorized_Code();
                Author.Code = pinCode;
                Author.Createdate = DateTime.Now;
                Author.During = 3600;
                Author.Email = user.EMAIL;
                userDB.InsertPinCode(Author);
                //send mail
                LKVMLMADMIN.Common.MailHelper.SendMail(user.EMAIL, subject, ContentMail);
                return Json(new { Result = "", Status = true, Messeger = "We are send pincode to your email. Please check mail !" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult ChangeAccPerfectMoney(AccPerfectMoneyView data)
        {
            try
            {
                //pincode
                var ExistCode = userDB.checkPinCode(data.PinCode);
                //change acc perfect money and email user
                if (ExistCode)
                {
                    //tru tien trong wallet
                    var transaction = new LKVService.Transaction();
                    var fee = userDB.getFeeConfig();
                    var isEmailInSytem = userDB.checkMailInSystemOtherUserID(data.Email,data.UserId);
                    if (isEmailInSytem) return Json(new { Result = "", Status = false, Messeger = "Email Exit in System" });
                    var isCashOut = transaction.chargeFormWallet(data.UserId, data.WalletId, -1*fee.PremiumEdit.Value, "Premium Edit User");                    
                    if (isCashOut)
                    {                                              
                        userDB.changeEmailByUserId(data.Email, data.UserId);
                        userDB.UpdatePerfectMoney(data.UserId, "USD", data.Payee_Account, data.Payer_Account, data.Payee_Name);
                        userDB.removePinCode(data.PinCode);
                        return Json(new { Result = "", Status = true, Messeger = "Change Email and Account Perfect Money Successful" });
                    }
                    return Json(new { Result = "", Status = false, Messeger = "Wallet Balance is not enough" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Not Exit Pin Code" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        /// <summary>
        /// Change account bit coin
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public ActionResult ChangeAccBitCoin(AccPerfectMoneyView data)
        {
            try
            {
                return Json(new { Result = "", Status = false, Messeger = "Not Exit Pin Code" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult Signup(SignIn register)
        {
            try
            {
                if (String.IsNullOrEmpty(register.UserName))
                    return Json(new { Result = "", Status = false, Messeger = "UserName is required" });
                if (String.IsNullOrEmpty(register.Password))
                    return Json(new { Result = "", Status = false, Messeger = "Password is required" });
                if(String.IsNullOrEmpty(register.Password2))
                    return Json(new { Result = "", Status = false, Messeger = "Confirm-Password is required" });
                if (String.IsNullOrEmpty(register.SecondPassword))
                    return Json(new { Result = "", Status = false, Messeger = "Password Level 2 is required" });
                if (String.IsNullOrEmpty(register.ConfirmSecondPassword))
                    return Json(new { Result = "", Status = false, Messeger = "Confirm-Password Level 2 is required" });
                if (String.IsNullOrEmpty(register.NganHang))
                    return Json(new { Result = "", Status = false, Messeger = "Bank is required" });
                if (String.IsNullOrEmpty(register.SDTNHARIENG))
                    return Json(new { Result = "", Status = false, Messeger = "Phone is required" });
                if(register.SecondPassword != register.ConfirmSecondPassword)
                    return Json(new { Result = "", Status = false, Messeger = "Password Level 2 and Confirm-Password Level 2 does not match" });
                //kiem tra mat khau va mat khau 2
                if (register.Password == register.Password2)
                {
                    UserProfile User = new UserProfile();                    
                    var groupDefault = userDB.getListGroup().Where(w => w.Default == true).FirstOrDefault();
                    User.GruopID = groupDefault.GroupID;
                    User.HOTEN = User.UserName;
                    LKVService.Transaction transaction = new LKVService.Transaction(); 
                    if(userDB.countBank(register.NganHang) > 3)
                        return Json(new { Result = "", Status = false, Messeger = "Bank number exceed the specified" });
                    if (userDB.countPhone(register.SDTNHARIENG) > 3)
                        return Json(new { Result = "", Status = false, Messeger = "Phone number exceed the specified" });
                    if (register.Sponsor==null)
                    {
                        register.Sponsor = "";
                    }
                    //check Sponsor
                    var Sponsor = userDB.findUserByUserName(register.Sponsor);                    
                    if (Sponsor != null)
                    {
                        User.Parent_ID = Sponsor.UserId;
                    }
                    else
                    {                        
                        return Json(new { Result = "", Status = false, Messeger = "No sponsor." });
                    }
                    if (register.Sponsor == null)
                    {
                        register.Sponsor = "";
                    }
                    User.Password = LKVMLMADMIN.Controllers.UserController.MD5Hash(register.Password);
                    User.p = register.Password;
                    User.UserName = register.UserName;
                    
                    if (userDB.checkUsernameInSystem(register.UserName))
                    {
                        return Json(new { Result = "", Status = false, Messeger = "The Username you entered is not available. Please pick another Username." });
                    }
                    User.HOTEN = register.HoTen;
                    User.SOCMND = register.SoCMND;
                    if(!register.Email.Contains("@"))
                        return Json(new { Result = "", Status = false, Messeger = "Email format is incorrect" });
                    User.EMAIL = register.Email;
                    User.SDTNHARIENG = register.SDTNHARIENG;
                    User.SoTaiKhoan = register.NganHang;
                    User.SecondPassword = LKVMLMADMIN.Controllers.UserController.MD5Hash(register.SecondPassword);
                    User.BankID = register.BankID == null ? 1 : register.BankID;
                    var result = userDB.AddUser(User,register.isLeft == false ? "Right" : "Left");
                    if (result>0)
                    {
                        //var bt = new BitcoinPaymentSevices();
                        //bt.addBitcoinAccount(new BitCoinUser { Payer = register.NganHang, UserId = result});
                        var userNew = userDB.findUserById(result);
                        if (userNew != null)
                        {
                            string contentMail = "<span>Dear " + userNew.HOTEN +"</span><br/>";
                            contentMail += "Welcome to Mybank.org<br/>";
                            contentMail += "Thank you for signing up with us and the followings are your details:  <br />";
                            contentMail += "<b>Name:</b>" + userNew.HOTEN + "<br/>";
                            contentMail += "<b>UserName:</b>" + userNew.UserName + "<br/>";
                            contentMail += "<b>Password:</b>" + register.Password + "<br/>";
                            contentMail += "<b>Email:</b>" + userNew.EMAIL + "<br/>";
                            contentMail += "<b>Mobile:</b>" + userNew.SDTNHARIENG + "<br/>";
                            contentMail += "Thank you for your support and we look forward to working with you ! <br/>";
                            contentMail += "Yours sincerely, <br/>";
                            contentMail += "The MyBanks Team, <br/>";
                            contentMail += "If you have any question, please drop us an email at: <br/>";
                            contentMail += "contact@mybanks.org <br/>";
                            contentMail += "http://www.mybanks.org";
                            LKVMLMADMIN.Common.MailHelper.SendMail(userNew.EMAIL, "MyBanks Support-Sigup Success", contentMail);
                        }
                        return Json(new { Result = "", Status = true, Messeger = "You have successfully registered ." });
                    }
                    else
                    {
                        return Json(new { Result = "", Status = false, Messeger = "L-R error" });
                    }                    
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Confirmation password does not match the password" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex });
            }            
        }
        public ActionResult GetReferral(int UserId)
        {
            UserProfile[] result;
            var list = new List<Referral>();
            try
            {
                result = userDB.getListByParent(UserId);                
                if (result != null)
                {
                    foreach (UserProfile item in result)
                    {                        
                        Referral User = new Referral();
                        LKVService.OrderService db = new LKVService.OrderService();
                        var totalMoney = db.GetOrderByUserID(item.UserId);
                        User.TotalMoney = totalMoney>0?totalMoney.ToString("0.00"):"0";
                        User.UserName= item.UserName;
                        User.TotalF1 = userDB.getListByParent(item.UserId).Count();
                        User.UserId = item.UserId;
                        User.Total = 2;// se lam sau
                        User.TotalPin = 1;// se lam sau

                        User.MemberShip = userDB.getUserLevelById((int)item.Level).Name;
                        User.Achievement = userDB.findAchievementByUserId(item.UserId).Name;
                        list.Add(User);
                    }
                }
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
            return Json(list);
        }
        public ActionResult GetReferralDetail(int UserId)
        {
            try
            {                
                //var user = userDB.findUserById(UserId);
                var transactionDB = new LKVService.Transaction();
                int totalUserF1 = userDB.totalUserF1(UserId);
                int totalUserF2 = userDB.totalUserF2(UserId);
                dynamic TotalUser = new System.Dynamic.ExpandoObject();
                TotalUser = userDB.totalUserF3(UserId);
                double TotalUpgradeCommission = transactionDB.getTotalUpgradeCommission(UserId).Value;
                var ListView = new List<LKVService.StatisticList>() { 
                    new LKVService.StatisticList {Id=1,Name="Total F1", Total=TotalUser.F1>0?TotalUser.F1.ToString():"0", Link="#" },
                    new LKVService.StatisticList {Id=2,Name="Total F2", Total=TotalUser.F2>0?TotalUser.F2.ToString():"0", Link="#" },
                    new LKVService.StatisticList {Id=3,Name="Total F3", Total=TotalUser.F3>0?TotalUser.F3.ToString():"0", Link="#" },
                    new LKVService.StatisticList {Id=4,Name="Pack Commission F1", Total=TotalUser.TotalCommissionF1>0?TotalUser.TotalCommissionF1.ToString("0.00"):"0", Link="#" },
                    new LKVService.StatisticList {Id=5,Name="Pack Commission F2", Total=TotalUser.TotalCommissionF2>0?TotalUser.TotalCommissionF2.ToString("0.00"):"0", Link="#" },
                    new LKVService.StatisticList {Id=6,Name="Pack Commission F3", Total=TotalUser.TotalCommissionF3>0?TotalUser.TotalCommissionF3.ToString("0.00"):"0", Link="#" },
                    new LKVService.StatisticList {Id=7,Name="Upgrade Commission", Total=TotalUpgradeCommission>0?TotalUpgradeCommission.ToString("0.00"):"0", Link="#" },
                };
                return Json(new { Result = ListView, Status = true, Messeger = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }           
        }
        public ActionResult GetParent(int UserId)
        {
            var result = new UserProfile();
            try
            {
                result = userDB.findParent(UserId);
            }
            catch (Exception ex)
            {
                return Json(ex);                
            }
            return Json(result);
        }
        public ActionResult Forgotpass(string UserName,string mail)
        {
            bool StatusFunction = false;
            try
            {
                //check email ton tai trong he thong
                var user = userDB.findUserByUserName(UserName.Trim());
                string messeger = "";
                if (user == null)
                {
                    return Json(new { Result = "", Status = StatusFunction, Messeger = "UserName not found" });
                }
                if (user.EMAIL != mail)
                {
                    return Json(new { Result = "", Status = StatusFunction, Messeger = "Email is invaild" });
                }
                //send pincode
                string pinCode = LKVMLMADMIN.Common.StringHelper.RandomString(10);
                string subject = "MyBanks Support - Forgot Password";
                string ContentMail = string.Format("New passowrd: {0}", pinCode);
                user.Password = LKVMLMADMIN.Controllers.UserController.MD5Hash(pinCode);
                user.p = pinCode;
                userDB.changPassword(user);
                //send mail
                LKVMLMADMIN.Common.MailHelper.SendMail(mail, subject, ContentMail);
                messeger = "An email has been sent to your email address. The email contains a new password, please login.";
                StatusFunction = true;
                return Json(new { Result = "", Status = StatusFunction, Messeger = messeger });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = StatusFunction, Messeger = ex.Message });
            } 
        }
        public ActionResult Contact(ContactForm contactform)
        {
            try
            {
                string messeger = "";
                if (contactform.Subject != "" && contactform.Subject != "")
                {
                    //get email admin
                    var ToEmailAddress = ConfigurationManager.AppSettings["ToEmailAddress"].ToString();
                    string ContentMail = string.Format("<p><strong>Email:</strong> {0}<br/>", contactform.Email);
                    ContentMail += string.Format("<strong>Subject:</strong> {0}<br/>", contactform.Subject);
                    if (contactform.UserName != "" && contactform.UserName != null) ContentMail += string.Format("<strong>UserName:</strong> {0}<br/>", contactform.UserName);
                    ContentMail += string.Format("<strong>Content:</strong> {0}</p>", contactform.Message);
                    //send mail
                    LKVMLMADMIN.Common.MailHelper.SendMail(ToEmailAddress, contactform.Subject, ContentMail);
                    messeger = "We are send email contact to Administrator.";
                    return Json(new { Result = "", Status = true, Messeger = messeger });
                }
                else
                {
                    messeger = "Please enter input field";
                    return Json(new { Result = "", Status = false, Messeger = messeger });
                }                
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            } 
        }
        public ActionResult ResetPass(string pincode)
        {
            try
            {
                var ExistCode = userDB.checkPinCode(pincode);
                if (ExistCode)
                {                    
                    //change pass
                    return Json(new { Result = pincode, Status = true, Messeger = "" });
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Not Exist PinCode Or PinCode time die" });
                }
                
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }           
        }
        public ActionResult ChangePassByPincode(string pincode, string password)
        {
            try
            {
                var ExistCode = userDB.checkPinCode(pincode);
                if (ExistCode)
                {
                    //change pass
                    //get mail find userid and change pass
                    UserProfile User = userDB.changePasswordByPincode(pincode, password);
                    if (User != null)
                    {
                        string subject = "";
                        string ContentMail = string.Format("Hello {0},\n\n Reset password successful.", User.HOTEN);
                        ContentMail +="Your account is created and must be activated before you can use it.";
                        ContentMail += string.Format("\n\nUsername: {0}\nPassword: {1}", User.UserName, password);
                        LKVMLMADMIN.Common.MailHelper.SendMail(User.EMAIL, subject, ContentMail);                        
                    }
                    //delete pincode
                    return Json(new { Result = pincode, Status = true, Messeger = "Reset password successful. You may now login to the site." });
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Not Exist PinCode" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }  
        }
        [HttpPost]
        public ActionResult UpgradeSuccessful()
        {
            var db = new LKVService.User();
            //db.UpgradeUser();
            return View();
        }
        public ActionResult UpgradeUser(int UserId, int LevelId, int WalletId, int Period)
        {
            try
            {                
                var transaction = new LKVService.Transaction();
                //get amount by level
                var level = userDB.getUserLevelById(LevelId);
                //get Wallet by Id
                var wallet = transaction.getWalletDetail(UserId, WalletId);
                var fees = level.Amount.Value * (float)Period;
                if(wallet.Balance>=fees)
                {
                   //pay when upgrade user
                   var paywallet = transaction.chargeFormWallet(UserId, WalletId,-1* fees, "Upgrade");
                   if (paywallet)
                   {
                       var upgradeUser = userDB.AfterUpgradeUser(UserId, LevelId, level.Amount.Value, null, null, DateTime.Now.AddMonths(Period));
                       return Json(new { Result = "", Status = true, Messeger = "Upgrade User Successful" });
                   }
                   else
                   {
                       return Json(new { Result = "", Status = false, Messeger = "Upgrade User Successful" });
                   }
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Upgrade User unsuccessful. Insufficient balance" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }            
        }
        public ActionResult GetUserLevel()
        {
            try
            {
                var userLevel = userDB.getUserLevels();
                return Json(new { Result = userLevel, Status = true, Messeger = "" }); 
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });                
            }
        }
        public ActionResult processPerfectMoney(LKVService.formPerfectTransaction data)
        {
            try
            {               
                var transaction = new LKVService.Transaction();
                var updateTransactionPerfectMoney = 0;
                //add or update
                if (data.UserId > 0)
                {
                    if (data.Payer_Account[0] == 'U' || data.Payer_Account[0] == 'u')
                    {
                        //isUpdateAccount = userDB.UpdatePerfectMoney(data.UserId, "USD", data.Payee_Account, data.Payer_Account, data.Payee_Name);
                        try
                        {
                            updateTransactionPerfectMoney = transaction.UpdatePerfectMoneyTransaction(data);
                            //add perfect transaction
                            if (updateTransactionPerfectMoney > 0)
                            {
                                return Json(new { Result = updateTransactionPerfectMoney, Status = true, Messeger = "Transaction Perfectmoney Successful" });
                            }
                            else
                            {
                                return Json(new { Result = "", Status = false, Messeger = "Could not update perfect money" });
                            }          
                        }
                        catch (Exception ext)
                        {
                            return Json(new { Result = "", Status = false, Messeger = ext.Message });
                        }
                    }
                    else
                    {
                        return Json(new { Result = "", Status = false, Messeger = "Only Support Units USD" });
                    }
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Not User Login" });
                }                
                      
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });                
            }
        }
        public ActionResult changePassword(FormChangePass Data)
        {
            try
            {
                var StringHelper = new Common.StringHelper();
                var User = userDB.findUserById(Data.UserId);
                if (User.Password == StringHelper.MD5Hash(Data.Password) && Data.Password1 == Data.Password2)
                {               
                    User.Password = StringHelper.MD5Hash(Data.Password1);
                    User.p = Data.Password1;
                    userDB.changPassword(User);
                    return Json(new { Result = "", Status = true, Messeger = "Change Passowrd successful" });
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Passwords do not match, Please check back" });
                }               
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult changeSecondPassword(SecondPasswordChange Data)
        {
            try
            {
                var StringHelper = new Common.StringHelper();
                var User = userDB.findUserById(Data.UserId);
                var ckPH = userDB.checkUserInPH(User.UserId);
                if (ckPH == true)
                {
                    return Json(new { Result = "", Status = false, Messeger = "Information cannot be changed while PH" });
                }
                if (User.SecondPassword == StringHelper.MD5Hash(Data.SecondPassword) && Data.SecondPassword1 == Data.SecondPassword2)
                {
                    userDB.changePasswordLevel2(User.UserId, Data.SecondPassword1);
                    return Json(new { Result = "", Status = true, Messeger = "Change Passowrd successful" });
                }
                else
                {
                    return Json(new { Result = "", Status = false, Messeger = "Passwords do not match, Please check back" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult getCountryList()
        {
            try
            {
                var CountryList = userDB.getCountryList();
                if (CountryList!=null)
                {
                    return Json(new { Result = CountryList, Status = true, Messeger = "" });
                }
                return Json(new { Result = "", Status = false, Messeger = "Loading country not data" });
            }
            catch (Exception ex)
            {
                
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }
        }
        public ActionResult CheckSession(string session)
        {            
            try
            {
                var sessionService = new LKVService.SystemService();
                var result = sessionService.CheckSession(session);
                if (result)
                {
                    return Json(new { Result = result, Status = true, Messeger = "" });
                }
                return Json(new { Result = result, Status = false, Messeger = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            }            
        }
        public ActionResult ClearSession(int UserId)
        {
            try
            {
                var sessionService = new LKVService.SystemService();
                var result = sessionService.ClearSessionUser(UserId);
                if (result)
                {
                    return Json(new { Result = result, Status = true, Messeger = "Clear session to successful" });
                }
                return Json(new { Result = result, Status = false, Messeger = "Clear session to unsuccessful" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = false, Messeger = ex.Message });
            } 
        }
        public JsonResult getRootTree(string id)
        {
            var extenssion = new LKVService.User();
            var usfind = extenssion.findUserByUserName(id);
            int UserId;
            if (usfind == null)
            {
                UserId = 0;
            }
            else
                UserId = usfind.UserId;
            var rootnode = extenssion.GetTreeRoot(UserId);
            return Json(rootnode, JsonRequestBehavior.AllowGet);
        }
        public JsonResult countChildBinary(string id)
        {
            var extenssion = new LKVService.User();
            var usfind = extenssion.findUserByUserName(id.Trim(new Char[] { '#' }));
            int UserId;
            Int32.TryParse(id, out UserId);
            var childBinary  = extenssion.countChildBinaryByParentBId(UserId);
            return Json( new { Status = true, BinaryChilds = childBinary} ,JsonRequestBehavior.AllowGet);
        }
        public JsonResult getTreeChildren(string id)
        {
            var extenssion = new LKVService.User();
            var usfind = extenssion.findUserByUserName("root");
            int UserId;
            if (usfind == null)
            {
                UserId = usfind.UserId;
            }
            else
                UserId = usfind.UserId;
            //var _tempDoc = extenssion.getTriAnTreeByLogOn(UserId);
            //get root node
            var rootnode = extenssion.GetTreeChildrenByRoot(int.Parse(id));
            return Json(rootnode, JsonRequestBehavior.AllowGet);
        }
        public JsonResult getInfomationByUserLogin(string id)
        {
            int userID = 0;
            Int32.TryParse(id, out userID);
            var db = new LKVService.User();
            var od = new LKVService.OrderService();
            var user = db.findUserById(userID);
            var cn_f1 = db.totalUserF1(userID);
            var cn_downline = db.getDownLine(userID);
            var od_invest = od.GetOrderByUserID(userID);
            var od_pin = 0;
            var level = "";
            if(db.findAchievementByUserId(userID)!=null)
                level=db.findAchievementByUserId(userID).Name;
            return Json(new { F1 = cn_f1, Invest = od_invest, Total = cn_downline, TotalPin = od_pin, Level = level,UserName = user.UserName,FullName = user.HOTEN });
        }
        public JsonResult getDocument(string id)
        {
            int userID = 0;
            Int32.TryParse(id, out userID);
            var doc = new DocumentUser()
            {
                Id = 0,
                Invest = 0,
                Downline = 0,
                TotalF1 = 0
            };
            var db = new LKVService.User();
            var user = db.findUserById(userID);
            if (user == null)
                return Json(new { doc = doc }, JsonRequestBehavior.AllowGet);
            doc.TotalF1 = db.totalUserF1(userID);
            doc.Downline = db.getDownLine(userID);
            doc.UserName = user.UserName;
            doc.FullName = user.HOTEN;
            if (db.findAchievementByUserId(userID) != null)
                doc.Level = db.findAchievementByUserId(userID).Name;
            else
                doc.Level = "";

            return Json(new { doc = doc }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult specifiedLeftRight(string id)
        {
            int userID = 0;
            Int32.TryParse(id, out userID);
            var db = new LKVService.User();
            var user = db.findUserById(userID);
            if (user == null)
                return Json(new {Status = false ,isLeft = false }, JsonRequestBehavior.AllowGet);
            if(user.Left == null)
                return Json(new { Status = true, isLeft = true }, JsonRequestBehavior.AllowGet);
            var lUser = db.findUserById(user.Left.Value);
            if(lUser != null)
                return Json(new { Status = false, isLeft = false }, JsonRequestBehavior.AllowGet);
            else
            { 
                return Json(new { Status = true, isLeft = true }, JsonRequestBehavior.AllowGet);
            }

            if (user.Right == null)
                return Json(new { Status = true, isLeft = false }, JsonRequestBehavior.AllowGet);
            var RUser = db.findUserById(user.Right.Value);
            if (RUser != null)
                return Json(new { Status = false, isLeft = false }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { Status = true, isLeft = false }, JsonRequestBehavior.AllowGet);

        }
        public ActionResult getListUserExceptUserLogin(string id)
        {
            try
            {
                int userId = 0;
                Int32.TryParse(id, out userId);
                var user = userDB.findUserById(userId);
                if (user == null)
                    return Json(new { Result = "", Status = false, Msg = "User does not exists in system" });

                var lsUser = userDB.getListUserExceptLogin(userId);
                if(lsUser.ToList().Count == 0)
                    return Json(new { Result = "", Status = false, Msg = "No data" });
                return Json(new { Result = lsUser, Status = true, Msg = "" });
            }
            catch (Exception ex)
            {

                return Json(new { Result = "", Status = false, Msg = ex.Message });
            }
        }
        public JsonResult getBank(int userId = 0)
        {
            var user = userDB.findUserById(userId);
            if(user == null)
                return Json(new { Status = false, Result = "", Msg = "" }, JsonRequestBehavior.AllowGet);
            var bank = userDB.findBankById(user.BankID != null ? user.BankID.Value : 0);
            if(bank == null)
                return Json(new { Status = false, Result = "", Msg = "" }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { Status = true, Result = bank, Msg = "" }, JsonRequestBehavior.AllowGet);
        }
        //Quên mật khẩu cấp 2
        public ActionResult ForgotSecondPass(string username, string mail)
        {
            bool StatusFunction = false;
            try
            {
                //check email ton tai trong he thong
                string messeger = "";
                var user = userDB.findUserByUserName(username.Trim());
                var checkPH = userDB.checkUserInPH(user.UserId);
                if(checkPH == true)
                {
                    return Json(new { Result = "", Status = StatusFunction, Messeger = "Password Level 2 cannot be changed while PH" });
                }
                
                if (user == null)
                {
                    return Json(new { Result = "", Status = StatusFunction, Messeger = "UserName not found" });
                }
                if (user.EMAIL != mail)
                {
                    return Json(new { Result = "", Status = StatusFunction, Messeger = "Email is invaild" });
                }
                //send pincode
                string pinCode = LKVMLMADMIN.Common.StringHelper.RandomString(10);
                string subject = "MyBanks Support - Forgot Password";
                string ContentMail = string.Format("New passowrd: {0}", pinCode);
                userDB.changePasswordLevel2(user.UserId,pinCode);
                //send mail
                LKVMLMADMIN.Common.MailHelper.SendMail(mail, subject, ContentMail);
                messeger = "An email has been sent to your email address. The email contains a new password level 2, please login.";
                StatusFunction = true;
                return Json(new { Result = "", Status = StatusFunction, Messeger = messeger });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "", Status = StatusFunction, Messeger = ex.Message });
            }
        }
        //Lấy parent 
        public ActionResult getParentById(int userId = 0)
        {
            var user = userDB.findUserById(userId);
            if(user == null)
                return Json(new { Result = "", Status = false, Msg ="Fail" });
            var pr = userDB.findParent(user.Parent_ID.Value);
            if(pr == null)
                return Json(new { Result = "", Status = false, Msg = "Fail" });
            return Json(new { Result = pr, Status = true, Msg = ""});
        }
    }
    public class Referral
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string MemberShip { get; set; }
        public string TotalMoney { get; set; }
        public int TotalF1 { get; set; }
        public int Total{ get; set; }
        public int    TotalPin{ get; set; }
        public string Achievement { get; set; }
    }
    public class SignIn
    {
        public string Sponsor { get; set; }
        public string Sponsor2 { get; set; }
        public string UserName { get; set; }
        public string HoTen { get; set; }
        public string SoCMND { get; set; }
        public string Email { get; set; }        
        public string Password { get; set; }
        public string Password2 { get; set; }
        public string SDTNHARIENG { get; set; }
        public bool isLeft { get; set; }// if isLeft == true then "Left" else "Right"
        public string NganHang { get; set; }// payer bitcoin
        public string SoTaiKhoan { get; set; }
        public string TenNganHang { get; set; }
        public string SecondPassword { get; set; }
        public string ConfirmSecondPassword { get; set; }
        public int? BankID { get; set; }
    }
    public class AccPerfectMoneyView
    {
        public int UserId { get; set; }
        public int WalletId { get; set; }
        public string Email { get; set; }
        public string Payee_Account { get; set; }
        public string Payer_Account { get; set; }
        public string Payee_Name { get; set; }
        public string PinCode { get; set; }

    }

    public class FormChangePass
    {
        public int UserId { get; set; }
        public string Password { get; set; }
        public string Password1 { get; set; }
        public string Password2 { get; set; }
    }
    public class SecondPasswordChange
    {
        public int UserId { get; set; }
        public string SecondPassword { get; set; }
        public string SecondPassword1 { get; set; }
        public string SecondPassword2 { get; set; }
    }
    public class ContactForm
    {
        public string UserName { get; set; }
        public string Email { get; set; }
        public string Subject { get; set; }
        public string Message { get; set; }
    }
    public class DocumentUser 
    {
        public int Id { get; set; }
        public int Downline { get; set; }
        public int TotalF1 { get; set; }
        public double Invest { get; set; }
        public string Level { get; set; }
        public string UserName { get; set; }
        public string FullName { get; set; }
    }
}
